import { relationList } from '../../menus/index';
import { validate, NULL_RULES } from '../../utils/validate';
import { addVisitor, getVisitorList, editVisitor } from '../../model/visitor';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

const app = getApp();

Page({
  data: {
    id: '',
    statue: '', // 页面状态 
    relationShow: false,
    relationList,
    relation: null as any,
    form: {
      name: '',
      phone: '',
      gender: 1,
      age: undefined,
      card_id: '',
      relation: 1
    },
    rules: {
      name: [{rule: NULL_RULES, msg: '就诊人姓名不能为空'}],
      gender: [{rule: NULL_RULES, msg: '就诊人性别不能为空'}],
      age: [{rule: NULL_RULES, msg: '就诊人年龄不能为空'}],
      phone: [{rule: NULL_RULES, msg: '手机号码不能为空'}],
      card_id: [{rule: NULL_RULES, msg: '身份证号码不能为空'}],
      relation: [{rule: NULL_RULES, msg: '就诊人关系不能为空'}]
    }
  },
  showRelationPicker() {
    this.setData({
      relationShow: true
    });
  },
  closeRelationPicker() {
    this.setData({
      relationShow: false
    });
  },
  selectRelation(event: any) {
    const data = event.detail.value;
    this.setData({
      relation: data,
      relationShow: false
    });
  },
  async submitForm(event: any) {
    const { name, gender, age, phone, card_id } = event.detail.value;
    const validateRes = validate(event.detail.value, this.data.rules);
    
    if (validateRes) {
      Dialog.alert({
        message: validateRes,
      });
      return;
    }

    let res;
    if (this.data.statue === 'edit') {
      res = await editVisitor({
        id: this.data.id,
        name, 
        gender, 
        age: Number(age), 
        phone, 
        card_id, 
        relation: this.data.relation!.value, 
        open_id: app.globalData.openId
      });
    } else {
      res = await addVisitor({
        name, 
        gender, 
        age: Number(age), 
        phone, 
        card_id, 
        relation: this.data.relation!.value, 
        open_id: app.globalData.openId
      });
    }

    if (res.code === 200) {
      wx.navigateBack();
    }
  },
  async getVisitor() {
    const data = await getVisitorList({ id: this.data.id });
    const visitor = data[0];
    if (visitor) {
      const relation = relationList.find(item => item.value === visitor.relation);
      this.setData({
        form: visitor,
        relation
      });
    }
  },
  onLoad(query) {
    const { statue, id = '' } = query;
    this.setData({
      id,
      statue
    });

    if (statue === 'edit' && id) {
      this.getVisitor();
    }
  }
});

export {};